﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Runtime.InteropServices;
using System.Net;
using System.Data.SqlClient;
using System.Media;
using System.Windows.Media.Animation;

namespace DiasEngineDate
{
    /// <summary>
    /// Login.xaml 的交互逻辑
    /// </summary>
    public partial class Login : Window
    {
        //引用配置文件库
        [DllImport("kernel32")]
        private static extern long WritePrivateProfileString(string section, string key, string val, string filePath);
        [DllImport("kernel32")]
        private static extern int GetPrivateProfileString(string section, string key, string def, StringBuilder retVal, int size, string filePath);
        


        //本原祖窗口
        public static Window LoginWIN;

        public static string serveraddr;
        public static string sqlname;
        public static string sqlpwd;
        public static string dataname;
        public static bool loginstate;

        //定义全局变量
        public static string SuserName;
        public static string Suser;//登录用户名
        public static string Saction;//登录操作 
        public static string SysInfo;//取得当前系统名称
        public static string Cip;//获取登录用户ip地址
        public static DateTime Logintime = DateTime.Now;//取得当前系统时间
        public static string SEname;//登录账户
        public static string SuserImg;//用户头像

        FunctionINC inc = new FunctionINC();

        public Login()
        {
            InitializeComponent();
        }

        private void Close_Btn(object sender, RoutedEventArgs e)
        {
            this.Close();
        }

        private void Login_Click(object sender, RoutedEventArgs e)
        {
            //按钮声音
            string aupath = @"Audio\Login.wav";
            inc.PlayerAudio(aupath);
                //登录窗口
                //取得用户输入数据

                string inUser = UserName.Text;
                string inUpwd = Encryption_Decryption.Encrypt(UserPassword.Password);
                //检测数据
                if (inUser == "" || inUpwd == "")
                {
                    MessageBox.Show("非法字符串？", "帐号和密码不能为空？请核对后操作？否则无法登录？");
                    return;

                }
                loginstate = Convert.ToBoolean(Encryption_Decryption.Decrypt(IniReadValue("LoginStata", "loginstata", AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini")));//读取并且解密
                serveraddr = Encryption_Decryption.Decrypt(IniReadValue("Server", "server", AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini"));//读取并且解密
                sqlname = Encryption_Decryption.Decrypt(IniReadValue("Database", "name", AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini"));
                sqlpwd = Encryption_Decryption.Decrypt(IniReadValue("Database", "pwd", AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini"));
                // if (IniReadValue("Database", "pwd", Application.ResourceAssembly + "\\Config.ini") != "")
                //{
                //  sqlpwd = Encryption_Decryption.Decrypt(IniReadValue("Database", "pwd", AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini"));
                //}
                //else
                //{
                //sqlpwd = "";
                //}

                dataname = Encryption_Decryption.Decrypt(IniReadValue("Dataname", "data", AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini"));
            
                if (serveraddr == "" || sqlname == "" || dataname == "" || sqlpwd == "")
                {
                    MessageBox.Show("无法连接数据库？", "请检查登录配置文件是否存在或服务器参数是否已经设置正确？");
                    return;
                }
                try
                {
                    //链接数据库，并且实现登录
                    Conning conn = new Conning();
                    string sqllogin = "select count(*) from Dias_SystemUser where EName=@ename and UserPassword=@upwd";
                    //检测数据库中是否存在EName和Password
                    SqlCommand cmd = new SqlCommand(sqllogin, conn.sqlconn);
                    cmd.Parameters.AddWithValue("@ename", inUser);
                    cmd.Parameters.AddWithValue("@upwd", inUpwd);
                    int count = (int)cmd.ExecuteScalar();
                    if (count > 0)
                    {
                        //Info l = new Info(cmd.ExecuteNonQuery().ToString() + "||||||||" + count);
                        //l.Show();
                        //如果登录成功，隐藏登录窗口、显示操作主界面。
                        //给全局变量 赋值
                        string sqlinusername = "select CName from Dias_SystemUser where EName=@user";
                        SqlCommand luncmd = new SqlCommand(sqlinusername, conn.sqlconn);
                        luncmd.Parameters.AddWithValue("@user", inUser);

                        string sqlimg = "select UserPhoto from Dias_SystemUser where EName=@user";
                        SqlCommand imgcmd = new SqlCommand(sqlimg, conn.sqlconn);
                        imgcmd.Parameters.AddWithValue("@user", inUser);

                        SuserName = inUser;
                        Suser = (string)luncmd.ExecuteScalar();
                        SuserImg = (string)imgcmd.ExecuteScalar();
                        SEname = inUser;
                        SysInfo = System.Net.Dns.GetHostName();
                        Cip = GetIP();

                        conn.sqlconn.Close();

                        //将登录事件写入数据库
                        //Sysdate sd = new Sysdate();
                        //sd.Sysdating(Suser, Cip, SysInfo, Logintime.ToString());
                        //string sqlloginfo = string.Format("insert into Sys_Login_Info(Sys_Name,Sys_Action,Sys_Info,Sys_Time)values('{0}','{1}','{2}','{3}')", Suser, Cip, SysInfo, Logintime);
                        //插入格式：防注入string.Format("insert into Dias_SystemUser(DName,CName,EName,Password,U_Right,Time)values('{0}','{1}','{2}','{3}','{4}','{5}')", UDepartment,Cname,Ename,Pwd,Uright,TimeNow);
                        //SqlCommand loginfocmd = new SqlCommand(sqlloginfo, conn.sqlconn);
                        //loginfocmd.ExecuteNonQuery();
                        //关闭数据库链接
                        //conn.sqlconn.Close();
                        //显示主窗口
                        if (loginstate)
                        {
                            //如果是记录密码保存用户名和密码
                            WritePrivateProfileString("LoginUser", "loginuser", Encryption_Decryption.Encrypt(UserName.Text.Trim()), AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini");//经过加密保存到配置文件Config.ini
                            WritePrivateProfileString("LoginPassword", "loginpassword", Encryption_Decryption.Encrypt(UserPassword.Password.Trim()), AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini");//经过加密保存到配置文件Config.ini
                        }
                        else
                        {
                            //如果是记录密码保存用户名和密码
                            WritePrivateProfileString("LoginUser", "loginuser", Encryption_Decryption.Encrypt(""), AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini");//经过加密保存到配置文件Config.ini
                            WritePrivateProfileString("LoginPassword", "loginpassword", Encryption_Decryption.Encrypt(""), AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini");//经过加密保存到配置文件Config.ini
                        }
                        this.Hide();
                        Main m = new Main();
                        m.Show();
                        //TheMainWin tmw = new TheMainWin();
                        //tmw.Show();
                    }
                    else
                    {
                        MessageBox.Show("登录失败？", "您的密码或者帐号错误？请重新输入？");

                    }
                }
                catch (Exception)
                {
                    MessageBox.Show("无法连接数据库？", "请检查登录配置文件是否存在或服务器参数是否已经设置正确？");
                }

        }

        //读取INI文件方法
        static public string IniReadValue(string Section, string Key, string filepath)
        {
            StringBuilder temp = new StringBuilder(255);
            int i = GetPrivateProfileString(Section, Key, "", temp, 255, filepath);
            return temp.ToString();
        }

        //获取IP地址
        protected string GetIP()
        {
            // 获得本机局域网IP地址
            System.Net.IPAddress ipAddr;
            ipAddr = new System.Net.IPAddress(Dns.GetHostByName(Dns.GetHostName()).AddressList[0].Address);
            return ipAddr.ToString();
        }

        //窗体加载时
        private void Window_Loaded(object sender, RoutedEventArgs e)
        {
            inc.Loadinglogin(loginbig,780,328);

            //获取焦点
            this.UserName.Focus();
            string str = Encryption_Decryption.Decrypt(IniReadValue("LoginStata", "loginstata", AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini"));
            if (str=="")
            {

            }
            else
            {
                //将用户和密码显示出来
                UserName.Text = Encryption_Decryption.Decrypt(IniReadValue("LoginUser", "loginuser", AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini"));
                UserPassword.Password = Encryption_Decryption.Decrypt(IniReadValue("LoginPassword", "loginpassword", AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini"));
                loginstate = Convert.ToBoolean(str);//读取并且解密
                this.SaveLoginInfo.IsChecked = loginstate;
            }

        }

        private void Button_Click(object sender, RoutedEventArgs e)
        {
            DateConfig dc = new DateConfig();
            dc.ShowDialog();
        }

        private void SaveLoginInfo_Click(object sender, RoutedEventArgs e)
        {
            //保存记录密码
            WritePrivateProfileString("LoginStata", "loginstata", Encryption_Decryption.Encrypt(SaveLoginInfo.IsChecked.ToString()), AppDomain.CurrentDomain.BaseDirectory + "\\Config.ini");//经过加密保存到配置文件Config.ini
        }
    }
}
